from tkinter import Scrollbar, VERTICAL

import mtvmengine
import tkinter as tk
import csv
from io import StringIO



#import tktable
def printToScreen(screen, spamReader):
    # limpiamos las listas
    clearListboxes(screen)
    
    # ingresamos los datos
    j=0;
    exclusion=1
    if exclusion == 0: exclusion = 1 # la primera linea del csv son los encabezados
    for row in spamReader:
        #print(row)
        if j>exclusion:
            i=0
            for dato in row:
                if i==0:
                    screen.valPaqList.insert(tk.END, dato)
                if i==1:
                    # optimistic value for dato - not printed to screen
                    pass 
                if i==2:
                    # optimistic value for dato - not printed to screen 
                    pass
                if i==3:
                    screen.unfListMed.insert(tk.END, screen.getRoundVal(dato)) 
                if i==4:
                    screen.unfListVar.insert(tk.END, screen.getRoundVal(dato)) 
                if i==5:
                    screen.swmegListMed.insert(tk.END, screen.getRoundVal(dato))
                if i==6:
                    screen.swmegListVar.insert(tk.END, screen.getRoundVal(dato)) 
                if i==7:
                    screen.pytListMed.insert(tk.END, screen.getRoundVal(dato)) 
                if i==8:
                    screen.pytListVar.insert(tk.END, screen.getRoundVal(dato)) 
                if i==9:
                    screen.triListMed.insert(tk.END, screen.getRoundVal(dato)) 
                if i==10:
                    screen.triListVar.insert(tk.END, screen.getRoundVal(dato)) 
                if i==11:
                    screen.betaListMed.insert(tk.END, screen.getRoundVal(dato)) 
                if i==12:
                    screen.betListVar.insert(tk.END, screen.getRoundVal(dato)) 
                if i==13:
                    screen.norListMed.insert(tk.END, screen.getRoundVal(dato)) 
                if i==14:
                    screen.norListVar.insert(tk.END, screen.getRoundVal(dato)) 
                i=i+1    
        j=j+1        


def clearListboxes(screen):
    screen.valPaqList.delete(0, tk.END)
    screen.unfListMed.delete(0, tk.END)
    screen.unfListVar.delete(0, tk.END) 
    screen.swmegListMed.delete(0, tk.END)
    screen.swmegListVar.delete(0, tk.END)
    screen.pytListMed.delete(0, tk.END)
    screen.pytListVar.delete(0, tk.END)
    screen.triListMed.delete(0, tk.END)
    screen.triListVar.delete(0, tk.END)
    screen.betaListMed.delete(0, tk.END)
    screen.betListVar.delete(0, tk.END)
    screen.norListMed.delete(0, tk.END)
    screen.norListVar.delete(0, tk.END)

    

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.createWidgets()
        
        self.master=master
        
    def yview(self, *args):
        self.valPaqList.yview(*args)
        self.unfListMed.yview(*args)
        self.unfListVar.yview(*args)
        self.swmegListMed.yview(*args)
        self.swmegListVar.yview(*args)
        self.pytListMed.yview(*args)
        self.pytListVar.yview(*args)
        self.triListMed.yview(*args)
        self.triListVar.yview(*args)
        self.betaListMed.yview(*args)
        self.betListVar.yview(*args)
        self.norListMed.yview(*args)
        self.norListVar.yview(*args)
    
    def createWidgets(self):
        
        ''' ***********************************************
        Definicion de los componentes de la pantalla
        ***************************************************'''
        ## Un frame para el header
        self.headerFrame= tk.Frame(self.master)
        self.headerFrame.grid(row=0,column=0)
        
        ## Un frame para las listas de valores 
        self.scrollFrame = tk.Frame(self.master)
        self.scrollFrame.grid(row=1, column=0)
        
        ## Un frame para el pie de la aplicacion
        self.footerFrame = tk.Frame(self.master)
        self.footerFrame.grid(row=2, column=0)
        
        
        self.scrollbar = Scrollbar(self.scrollFrame, orient=VERTICAL)
        self.scrollbar.grid(row=2, column=15, sticky="ns")
        self.scrollbar.config(command=self.yview)
        
        self.L1 = tk.Label(self.headerFrame, text="Inicial")
        self.L1.grid(row=0)
        
        self.E1 = tk.Entry(self.headerFrame, width=5)
        self.E1.grid(row=0, column=1)
        self.E1.insert(0,"8")

        self.L2 = tk.Label(self.headerFrame, text="Final")
        self.L2.grid(row=1)
        
        self.E2 = tk.Entry(self.headerFrame, width=5)
        self.E2.grid(row=1, column=1)
        self.E2.insert(0,"80")

        
        #==============valor del paquete====================
        
        self.L6 = tk.Label(self.scrollFrame, text="       Horas      ")
        self.L6.grid(row=0, column=0)
        
        self.valPaqList = tk.Listbox(self.scrollFrame,height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.valPaqList.grid(row=2, column=0)
        
        #==============Distribucion uniforme====================
        
        self.L3 = tk.Label(self.scrollFrame, text="Uniforme")
        self.L3.grid(row=0, column=1, columnspan=2)
        
        self.L5 = tk.Label(self.scrollFrame, text="Media")
        self.L5.grid(row=1, column=1)
        
        self.unfListMed = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.unfListMed.grid(row=2, column=1)

        self.L7 = tk.Label(self.scrollFrame, text="Varianza")
        self.L7.grid(row=1, column=2)
        
        self.unfListVar = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.unfListVar.grid(row=2, column=2)
        
        #==============Distribucion Swanson and Megill====================
        
        self.L4 = tk.Label(self.scrollFrame, text="Swanson and Megill")
        self.L4.grid(row=0, column=3, columnspan=2)
        
        self.L8 = tk.Label(self.scrollFrame, text="Media")
        self.L8.grid(row=1, column=3)
        
        self.swmegListMed = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.swmegListMed.grid(row=2, column=3)
        
        self.L9 = tk.Label(self.scrollFrame, text="Varianza")
        self.L9.grid(row=1, column=4)
        
        self.swmegListVar = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.swmegListVar.grid(row=2, column=4)
        
        #==============Distribucion Pearson & Tuckey====================
        
        self.L10 = tk.Label(self.scrollFrame, text="Pearson & Tuckey")
        self.L10.grid(row=0, column=5, columnspan=2)
        
        self.L11 = tk.Label(self.scrollFrame, text="Media")
        self.L11.grid(row=1, column=5)
        
        self.pytListMed = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.pytListMed.grid(row=2, column=5)
        
        self.L12 = tk.Label(self.scrollFrame, text="Varianza")
        self.L12.grid(row=1, column=6)
        
        self.pytListVar = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.pytListVar.grid(row=2, column=6)
        
        #==============Distribucion Triangular====================
        
        self.L13 = tk.Label(self.scrollFrame, text="Triangular")
        self.L13.grid(row=0, column=7)
        
        self.L14 = tk.Label(self.scrollFrame, text="Media")
        self.L14.grid(row=1, column=7)
        
        self.triListMed = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.triListMed.grid(row=2, column=7)
        
        self.L15 = tk.Label(self.scrollFrame, text="Varianza")
        self.L15.grid(row=1, column=8)
        
        self.triListVar = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.triListVar.grid(row=2, column=8)
        
        
        #==============Distribucion Beta====================
        
        self.L16 = tk.Label(self.scrollFrame, text="Beta")
        self.L16.grid(row=0, column=9)
        
        self.L17 = tk.Label(self.scrollFrame, text="Media")
        self.L17.grid(row=1, column=9)
        
        self.betaListMed = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.betaListMed.grid(row=2, column=9)
        
        self.L18 = tk.Label(self.scrollFrame, text="Varianza")
        self.L18.grid(row=1, column=10)
        
        self.betListVar = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.betListVar.grid(row=2, column=10)
        
        #==============Distribucion Normal====================
        
        self.L19 = tk.Label(self.scrollFrame, text="Normal")
        self.L19.grid(row=0, column=11)
        
        self.L20 = tk.Label(self.scrollFrame, text="Media")
        self.L20.grid(row=1, column=11)
        
        self.norListMed = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.norListMed.grid(row=2, column=11)
        
        self.L21 = tk.Label(self.scrollFrame, text="Varianza")
        self.L21.grid(row=1, column=12)
        
        self.norListVar = tk.Listbox(self.scrollFrame, height=35, width=10, yscrollcommand=self.scrollbar.set)
        self.norListVar.grid(row=2, column=12)
        

        self.genData = tk.Button(self.footerFrame)
        self.genData["text"] = "Generar datos"
        self.genData["command"] = self.generateData
        self.genData.grid(row=0, column=1)
        
        self.L22 = tk.Label(self.footerFrame, text="  Nombre del Archivo: ")
        self.L22.grid(row=0, column=2)
        
        self.fileName = tk.Entry(self.footerFrame, width=20)
        self.fileName.grid(row=0, column=3)
        
        self.L23 = tk.Label(self.footerFrame, text="     ")
        self.L23.grid(row=0, column=4)
        
        self.hi_there = tk.Button(self.footerFrame)
        self.hi_there["text"] = "Crear Archivo"
        self.hi_there["command"] = self.generateCVS
        self.hi_there.grid(row=0, column=5)

        self.L24 = tk.Label(self.footerFrame, text="     ")
        self.L24.grid(row=0, column=6)
        
        self.isChecked=tk.BooleanVar()
        self.checkComma = tk.Checkbutton(self.footerFrame, text="Separar decimales con coma?", variable=self.isChecked, onvalue=True, offvalue=False)
        self.checkComma.grid(row=0, column=7)
        self.checkComma.select()
        self.L25 = tk.Label(self.footerFrame, text="     ")
        self.L25.grid(row=0, column=8)
        
        
        self.QUIT = tk.Button(self.footerFrame, text="SALIR", fg="red", command=root.destroy)
        self.QUIT.grid(row=0, column=9)
        
        
    def getRoundVal(self, val):
        '''******************************************************************
        Funcion utilizada para dar formato a los numeros que vienen en el csv
        ******************************************************************'''
        s=val.replace(",",".")
        return str(round(float(s),3))

    def generateCVS(self):
        '''******************************************************************
        Se genera el csv tomando los parametros inicial y final de la pantalla.
        Luego de ser generado el archivo, el mismo se carga en pantalla.
        ******************************************************************'''
        if self.E1.get() != "" and self.E2.get() !="":
            mtvmengine._initial=int(self.E1.get())
            mtvmengine._final=int(self.E2.get())+1
            nomFile=None
            # Determinamos si la salida debe usar la coma como delimitador o el punto
            conComa=True
            if self.isChecked.get()==0:
                conComa=False
            if self.fileName.get()!="":
                # generamos el archivo con el nombre ingresado en la UI y obtenemos el path
                nomFile=mtvmengine.createFile(self.fileName.get()+".csv", conComa)
            else: 
                # generamos el archivo y obtenemos el path
                nomFile = mtvmengine.createFile(floatComma=conComa)
            # parseamos
            spamReader = csv.reader(open(nomFile), delimiter=';', quotechar='|')
            # muestro en pantalla
            printToScreen(self, spamReader)        


    def generateData(self):
        '''******************************************************************
        Se genera el csv tomando los parametros inicial y final de la pantalla.
        Luego de ser generado, pero no guardado en disco, el mismo se carga en pantalla.
        ******************************************************************'''
        if self.E1.get() != "" and self.E2.get() !="":
            mtvmengine._initial=int(self.E1.get())
            mtvmengine._final=int(self.E2.get())+1
            csvContent = mtvmengine.generateData()
            strFile = StringIO(csvContent)
            spamReader = csv.reader(strFile, delimiter=';')
            printToScreen(self, spamReader)

        
# Main 
if __name__ == '__main__':
    root = tk.Tk()
    root.geometry("900x700")
    app = Application(master=root)
    app.mainloop()
 
